package com.sacc.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.power.common.model.CommonResult;
import com.sacc.clients.BoxClient;
import com.sacc.clients.ProductClient;
import com.sacc.mapper.OrderStateAllMapper;
import com.sacc.pojo.*;
import com.sacc.service.OrderDoneService;
import com.sacc.service.OrderStateAllService;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author 滚~韬
 * @date 2022/4/8 14:10
 */
@Service
public class OrderStateAllServiceImpl implements OrderStateAllService {
    @Autowired
    private OrderDoneService orderDoneService;
    @Autowired
    private OrderStateAllMapper orderStateAllMapper;
    @Autowired
    private ProductClient productClient;
    @Autowired
    private BoxClient boxClient;
    /**
     * 获取用户的所有订单信息
     * @param openId
     * @return
     */
    public List<OrderStateAll> getOrder(String openId){
        return  orderStateAllMapper.selectList(new QueryWrapper<OrderStateAll>().eq("open_id",openId));
    }

    /**
     * 获取用户对应状态的订单信息
     * @param openId
     * @param state
     * @return
     */
    //利用用户id和查询状态找到所有订单号,根据所查orderstateall去找到所属的productids和productlist
    public List<OrderList> getOrderByState(String openId,Integer state){
        List<OrderStateAll> orderStateAlls = orderStateAllMapper.selectList(new QueryWrapper<OrderStateAll>()
                .eq("open_id", openId)
                .eq("state", state));
        List<OrderList> orderLists = new ArrayList<>();
        orderStateAlls.forEach(o->{
            OrderList orderList = new OrderList();
            //string转list,存多个productid
            List<Integer> productIds = Arrays.asList((Integer[]) ConvertUtils.convert(o.getProductIds().split(","), Integer.class));
            //string转list,存多个productNumber
            List<Integer> productNumbers = Arrays.asList((Integer[])ConvertUtils.convert(o.getProductNumbers().split(","), Integer.class));
            List<ProductInfoAll> productInfoAlls = new ArrayList<>();
            productIds.forEach(p->{
                if(p>1000){
                    BoxAll box = boxClient.getBox(p);
                    ProductInfoAll temp = new ProductInfoAll();
                    temp.setProductId(box.getBoxId());
                    temp.setPaidNumber(0);
                    temp.setProductName(box.getBoxName());
                    temp.setProductDetail(box.getBoxDesc());
                    temp.setProductPrice(box.getBoxPrice());
                    temp.setProductOriginId(0);
                    temp.setImageUrl(box.getBoxImageUrl());
                    temp.setCreateTime(box.getCreateTime());
                    productInfoAlls.add(temp);
                }else {
                    productInfoAlls.add(productClient.GetProductOneList(p));
                }
            });
            orderList.setCourierNumber(o.getCourierNumber());
            orderList.setProductNumber(productNumbers);
            orderList.setOrderNumber(o.getOrderNumber());
            orderList.setProductInfoAlls(productInfoAlls);
            orderLists.add(orderList);
        });
        return  orderLists;
    }

    /**
     * 更新订单进入下一层状态,是3就进入完成订单表里,并变成4表示最终状态,1代表待支付,2代表待发货,3代表待收货,4代表完成
     * @param orderNumber
     * @return
     */
    public CommonResult GoNextState(String orderNumber){
        try {
            OrderStateAll orderStateAll = orderStateAllMapper.
                    selectOne(new QueryWrapper<OrderStateAll>().eq("order_number", orderNumber));
            if (orderStateAll.getState() == 3) {
                OrderDone orderDone = new OrderDone();
                orderDone.setOrderNumber(orderStateAll.getOrderNumber());
                orderDone.setOpenId(orderStateAll.getOpenId());
                orderDone.setProductIds(orderStateAll.getProductIds());
                orderDone.setProductPrices(orderStateAll.getProductPrices());
                orderDone.setProductNumbers(orderStateAll.getProductNumbers());
                orderDone.setCreateTime(LocalDateTime.now());
                orderDoneService.AddOrderDone(orderDone);
            } else {
                orderStateAll.setState(orderStateAll.getState() + 1);
                orderStateAllMapper.updateById(orderStateAll);
            }
            return new CommonResult("200", "成功更新order_state");
        }catch (Exception e){
            return new CommonResult("400","失败更新order_state");
        }
    }


    /**
     * 创建订单号
     * @param orderStateAll
     * @return
     */
    public CommonResult CreateOrderNumber(OrderStateAll orderStateAll){
        try {
            Random random = new Random();
            StringBuilder stringBuilder = new StringBuilder();
            for (int i = 0; i < 2; i++) {
                stringBuilder.append(random.nextInt(9));
            }
            String s = String.valueOf(LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8"))).substring(0, 8);
            if(StringUtils.isNumeric(orderStateAll.getProductIds())){
                Integer i = Integer.valueOf(orderStateAll.getProductIds());
                if(i>1000){
                    boxClient.Adopt(orderStateAll.getOpenId(),orderStateAll.getProductIds());
                }
            }
            orderStateAll.setState(0);
            orderStateAll.setCreateTime(LocalDateTime.now());
            orderStateAll.setOrderNumber(s + orderStateAll.getOpenId().substring(4,8)+stringBuilder.toString());
            orderStateAllMapper.insert(orderStateAll);
            return new CommonResult(true,"插入成功",orderStateAll);
        } catch (Exception e){
            return new CommonResult(false,"插入失败:"+e.toString(),orderStateAll);
        }
    }

    /**
     * 取消订单号
     * @param orderNumber
     * @return
     */
    public CommonResult DeleteOrderNumber(String orderNumber){
        try{
            orderStateAllMapper.deleteById(orderNumber);
            return new CommonResult(true,"删除成功",orderNumber);
        }catch (Exception e){
            return new CommonResult(false,"删除失败:"+e.toString(),orderNumber);
        }


    }

    /**
     * 添加快递号
     * @param courierNumber
     * @return
     */
    @Override
    public CommonResult AddCourierNumber(String orderNumber,String courierNumber) {
        try{
            OrderStateAll orderStateAll = orderStateAllMapper.selectById(orderNumber);
            orderStateAll.setCourierNumber(courierNumber);
            orderStateAllMapper.updateById(orderStateAll);
            return new CommonResult(true,"更新快递号成功",courierNumber);
        }catch (Exception e){
            return new CommonResult(false,"更新快递号失败:"+e.toString(),courierNumber);
        }
    }

    /**
     * 得到一个订单的快递号
     * @param orderNumber
     * @return
     */
    @Override
    public CommonResult GetCourierNumber(String orderNumber) {
            return new CommonResult(true,"成功获取快递号",orderStateAllMapper.selectById(orderNumber).getCourierNumber());
    }
}
